<script lang="ts" setup>
import { computed } from 'vue'
import { useScrollTo } from '@/hooks/event/useScrollTo'

const props = defineProps({
  // 总数
  total: {
    required: true,
    type: Number
  },
  // 当前页数
  page: {
    type: Number,
    default: 1
  },
  // 每页个数
  limit: {
    type: Number,
    default: 10
  },
  // 组件布局，子组件名用逗号分隔
  layout: {
    type: String,
    default: 'total,sizes, prev, pager, next, jumper,'
  },
  // 是否为分页按钮添加背景色
  background: {
    type: Boolean,
    default: true
  },
  // 是否在切换页时自动回到顶部
  autoScroll: {
    type: Boolean,
    default: true
  }
})

const emits = defineEmits(['update:page', 'update:limit', 'pagination', 'pageSizeChange'])

const currentPage = computed({
  get: () => props.page,
  set: val => {
    emits('update:page', val)
    if (val !== props.page) {
      handleCurrentChange(val)
    }
  }
})

const pageSize = computed({
  get: () => props.limit,
  set: val => {
    emits('update:limit', val)
    if (val !== props.limit) {
      handlePageSizeChange(val)
    }
  }
})

/**
 * 当前页 改变时会触发
 * @param val 页数
 */
const handleCurrentChange = (val: number) => {
  emits('pagination', { page: val, limit: pageSize.value })
  if (props.autoScroll) {
    useScrollTo(0, 800, () => {})
  }
}

/**
 * page-size 改变时会触发
 * @param val 页数
 */
const handlePageSizeChange = (val: number) => {
  emits('pageSizeChange', val)
  if (props.autoScroll) {
    useScrollTo(0, 800, () => {})
  }
}
</script>

<template>
  <div class="pagination-container">
    <el-pagination
      :background="background"
      :page-sizes="[10, 20, 30, 50, 100]"
      :total="total"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :layout="layout"
      v-bind="$attrs"
    />
  </div>
</template>

<style lang="scss" scoped>
.pagination-container {
  display: flex;
  padding: 15px 16px;
  border-radius: 5px;
  justify-content: center;
}

.pagination-container.hidden {
  display: none;
}

.el-pagination {
  overflow: hidden;
}
</style>
